<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\home\controller;

use api\index\controller\CommonController;
use api\index\controller\UploadController;
use app\admin\model\ChangeCoinModel;
use app\admin\model\CommonModel;
use app\admin\model\FavoriteModel;
use app\admin\model\GradeRuleModel;
use app\admin\model\InfoSetModel;
use app\admin\model\LoginRecordModel;
use app\admin\model\MemberModel;
use app\admin\model\MobileCodeModel;
use app\admin\model\ReadLookModel;
use app\admin\model\UserTokenModel;
use cmf\controller\RestBaseController;
use cmf\lib\Storage;
use Endroid\QrCode\QrCode;
use think\Db;

//会员
class MemberController extends RestBaseController
{
    protected $noNeedLogin = ['login', 'mobileLogin'];

    //用户登录
    public function login()
    {
        if ($this->request->isGet()) {
            $code = $this->request->get('code');
            $rule = config('verify.user');
            $this->checkValidate(['code' => $code], $rule);

            //服务号配置
            $config = config('verify.raw');
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $config['app_id'] . '&secret=' . $config['app_secret'] . '&code=' . $code . '&grant_type=authorization_code';
            $res = CommonController::http_get($url);
            $json_arr = json_decode($res, true);
            if (!isset($json_arr['access_token']) && empty($json_arr['access_token'])) {
                $this->error('无效的access_token');
            }

            $access_token = $json_arr['access_token'];
            $openid = $json_arr['openid'];
            //通过access_token获取用户信息
            $info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
            $result = CommonController::http_get($info_url);
            $info = json_decode($result, true);
            //数据库新增或修改用户
            $where = ['openid' => $info['openid']];
            $ret = CommonController::findWhereData('member', $where, 'id');
            $member['openid'] = $info['openid'];
            if (isset($info['unionid'])) {
                $member['unionid'] = $info['unionid'];
            }
            $memberModel = new MemberModel();
            if ($ret) {
                $memberModel->allowField(true)->where($where)->update($member);
                $is_new = MemberModel::NEW_NO;//非新人
            } else {
                $member['avatar'] = $info['headimgurl'];
                $member['nickname'] = $info['nickname'];
                $member['sex'] = $info['sex'];
                $member['province'] = $info['province'];
                $member['city'] = $info['city'];
                $memberModel->allowField(true)->create($member);
                $is_new = MemberModel::NEW_YES;//新人
            }
            //查询用户表获取token
            $token = $this->getToken($where);
            $this->success("登录成功！", ['token' => $token['token'], 'is_new' => $is_new]);
        } else {
            $this->error('请求方式错误');
        }
    }

    //手机号登录
    public function mobileLogin()
    {
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $rule = config('verify.mobile_login');
            $this->checkValidate($data, $rule);

            //验证验证码是否正确
            //$this->validateMobileCode($data);

            //查询用户表获取token
            $token = $this->getToken(['mobile' => $data['mobile']]);
            $this->success("登录成功！", ['token' => $token['token']]);
        } else {
            $this->error('请求方式错误');
        }
    }

    //绑定手机号
    public function bindMobile()
    {
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $rule = config('verify.mobile_login');
            $this->checkValidate($data, $rule);

            //验证验证码是否正确
            //$this->validateMobileCode($data);
            //检测手机号是否已有人绑定
            $member_id = $this->getUserId();
            $where[] = ['id', '<>', $member_id];
            $where[] = ['mobile', '=', $data['mobile']];
            $is_bind = CommonController::findWhereData('member', $where, 'id');
            if ($is_bind) {
                $this->error('该手机号已被其他人绑定');
            }

            $memberModel = new MemberModel();
            $res = $memberModel->allowField(true)->save($data, ['id' => $member_id]);
            if ($res) {
                $this->success('绑定成功');
            } else {
                $this->error('绑定失败');
            }
        } else {
            $this->error('请求方式错误');
        }
    }

    //验证验证码是否正确
    private function validateMobileCode($data)
    {
        $mobileCodeModel = new MobileCodeModel();
        $res = $mobileCodeModel
            ->where(['mobile' => $data['mobile'], 'mobile_code' => $data['mobile_code'], 'is_use' => 0, 'create_date' => date('Y-m-d')])
            ->where('expire_time', 'gt', time())
            ->find();
        if ($res) {
            $mobileCodeModel->where('id', $res['id'])->setField('is_use', 1);
        } else {
            $this->error('验证未通过');
        }
    }

    //获取token
    private function getToken($where)
    {
        $memberModel = new MemberModel();
        $token = [];
        $findUser = CommonController::findWhereData('member', $where, 'id');
        if (empty($findUser)) {
            $this->error('用户不存在');
        } else {
            $findUserToken = CommonController::findWhereData('user_token', ['user_id' => $findUser['id']], 'id');
            $token['create_time'] = time();
            $token['expire_time'] = $token['create_time'] + 24 * 3600;
            $token['token'] = md5(uniqid()) . md5(uniqid());
            $tokenModel = new UserTokenModel();
            if (empty($findUserToken)) {
                $token['user_id'] = $findUser['id'];
                $result = $tokenModel->create($token);
            } else {
                $result = $tokenModel->where('user_id', $findUser['id'])->update($token);
            }
            //新增登录次数
            $loginModel = new LoginRecordModel();
            $login_time = strtotime(date('Y-m-d', time()));
            $loginModel->create(['member_id' => $findUser['id'], 'login_time' => $login_time]);
            //查询登录天数
            $login_day = CommonController::totalGroup('login_record', ['member_id' => $findUser['id']], 'login_time');
            //更新登录天数
            $memberModel->where(['id' => $findUser['id']])->update(['login_day' => $login_day]);
        }
        if (empty($result)) {
            $this->error("登录失败！");
        }
        return $token;
    }

    //获取个人信息
    public function info()
    {
        if ($this->request->isGet()) {
            //查询等级规则表
            $res_grade = CommonController::selectData('grade_rule', 'id,login_day,coin', 'id asc');
            //连续登录的天数
            $login_day = MemberModel::value('login_day');
            $level = MemberModel::DEFAULT_LEVEL; //默认等级 0
            $gain_coin = MemberModel::DEFAULT_COIN; //默认球币 0
            foreach ($res_grade as $key => $value) {
                if ($login_day >= $value['login_day']) {
                    $level = $value['grade'];
                    $gain_coin = $value['coin'];
                }
            }
            $member_id = $this->getUserId();
            //更新等级
            if ($level != MemberModel::DEFAULT_LEVEL) {
                MemberModel::where('id', $member_id)->update(['level' => $level]);
            }
            //增加球币
            if ($gain_coin != MemberModel::DEFAULT_COIN) {
                MemberModel::where('id', $member_id)->setInc('coin', $gain_coin);
            }
            //根据VIP到期时间更新是否为VIP
            $member = MemberModel::get($this->getUserId());
            if ($member) {
                if ($member['is_vip'] == MemberModel::IS_VIP) {
                    if ($member['last_time'] < time()) {
                        //更新为非VIP
                        MemberModel::where('id', $member_id)->update(['is_vip' => MemberModel::NOT_VIP]);
                    }
                }
            }

            //获取用户数据
            $res = CommonController::findWhereData('member', ['id' => $this->getUserId()], '*');

            if ($res) {
                $res['birthday'] = !empty($res['birthday']) ? date('Y/m/d', $res['birthday']) : '';
                $res['last_time'] = !empty($res['last_time']) ? date('Y-m-d H:i:s', $res['last_time']) : '';
                //可提现金额
                $rate = InfoSetModel::value('rate');
                $res['exchange_price'] = sprintf("%.2f", $res['coin'] / $rate);
                //总登录天数
                $res['max_login_day'] = GradeRuleModel::order('id desc')->value('login_day');
                $res['read_task'] = $member->task(ReadLookModel::TYPE_READ); //是否完成今天阅读任务
                $res['look_task'] = $member->task(ReadLookModel::TYPE_LOOK); //是否完成今天看视频任务
                $res['sign_task'] = CommonController::interval_day($member->id) ? false : true;//是否完成今天签到任务
                unset($res['create_time'], $res['update_time'], $res['expire_time']);
            }
            $this->success('成功', $res);
        } else {
            $this->error('请求方式错误');
        }
    }

    //获取信息配置
    public function infoSet()
    {
        if ($this->request->isGet()) {
            $commonModel = new CommonModel();
            //获取信息设置
            $res = CommonController::findWhereData('info_set', ['id' => 1], '*');
            $res['sign_rule'] = $commonModel->getPostContentAttr($res['sign_rule']);
            $res['grade_rule'] = $commonModel->getPostContentAttr($res['grade_rule']);
            $res['invite_rule'] = $commonModel->getPostContentAttr($res['invite_rule']);
            $res['guess_rule'] = $commonModel->getPostContentAttr($res['guess_rule']);
            $res['about_us'] = $commonModel->getPostContentAttr($res['about_us']);
            //连续登录天数
            $days = CommonController::interval_day($this->getUserId());
            //最近的签到数据
            $recentlySign = CommonController::findWhereData('sign_record', ['menber_id' => $this->getUserId()], '', 'create_time desc');
            //判断签到隔断是否超过一天或者已经签满30天
            if ($days > 1 || $recentlySign['con_coin'] == 30) {
                $day_num = 0;
            } else {
                //连续签到天数
                $day_num = $recentlySign['con_coin'];
            }
            if($sign_set = CommonController::findWhereData('sign_set', ['day' => $day_num + 1], 'get_coin')){
                $res['sign_coin'] = $sign_set['get_coin'];
            }
            //邀好友获得球币含邀请次数
            $count = ChangeCoinModel::where(['member_id' => $this->getUserId(), 'type' => ChangeCoinModel::INVITE])->count();
            $res['origin_coin'] = $res['origin_coin'] + $count * $res['incre_coin'];
            unset($res['create_time'], $res['update_time']);
            $this->success('成功', $res);
        }else{
            $this->error('请求方式错误');
        }
    }

    //修改个人信息
    public function updateInfo()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $memberModel = new MemberModel();
            $res = $memberModel->allowField(true)->save($data, ['id' => $this->getUserId()]);
            if ($res) {
                $this->success('修改成功');
            } else {
                $this->error('失败');
            }
        } else {
            $this->error('请求方式错误！');
        }
    }

    //等级规则列表
    public function gradeList()
    {
        $grade = GradeRuleModel::field('id,login_day,grade,coin')->select();
        $this->success('成功', $grade);
    }

    //球币记录列表
    public function coinRecordList()
    {
        if ($this->request->isGet()) {
            $type = $this->request->get('type');
            $page = $this->request->get('page');//分页页码
            $rule = config('verify.coin_record_list');
            $this->checkValidate(['type' => $type, 'page' => $page], $rule);

            $where['member_id'] = $this->getUserId();
            if ($type == ChangeCoinModel::IN_TYPE) {
                //收入
                $where['type'] = ChangeCoinModel::IN;
            } else if ($type == ChangeCoinModel::OUT_TYPE) {
                //支出
                $where['type'] = ChangeCoinModel::OUT;
            }
            $res = CommonController::selectWherePageData('change_coin', $where, $page, 'id,change_detail,change_coin,create_time');
            foreach ($res as &$value) {
                $value['create_time'] = date('Y/m/d H:i', $value['create_time']);
            }
            $total_page = CommonController::totalWherePage('change_coin', $where);
            $this->success('成功', ['data' => $res, 'last_page' => $total_page]);

        } else {
            $this->error('请求方式错误');
        }
    }

    //生成二维码
    public function getWxCode()
    {
        if ($this->request->isGet()) {
            $member_id = $this->getUserId();
            $qrCode = new QrCode();
            $qrCode->setText('http://liaogeqiu365.cmdfut.com?share_member_id=' . $member_id)
                ->setSize(300)
                ->setPadding(10)
                ->setErrorCorrection('high')
                ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
                ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
                ->setLabelFontSize(16)
                ->setImageType(QrCode::IMAGE_TYPE_PNG);

            $qrCode->save('upload/wx_code/wx_' . $member_id . '.png');
            //上传至七牛云
            $qiniu_file = 'wx_code/wx_' . $member_id . '.png';
            $image_relation_url = 'upload/'.$qiniu_file;//图片相对路径
            $img_url = \think\facade\Env::get('root_path').'/public/'.$image_relation_url;
            $storage = new Storage();
            $qi_res = $storage->upload($qiniu_file, $img_url, 'image');
            if($qi_res){
                $host = config('verify.host');
                $code_url = $host.$qiniu_file;
                $upload = new UploadController();
                $sys = $upload->getOperateSys();
                if($sys == 'Linux'){
                    unlink($img_url);//适用于linux
                }
            }else{
                $this->error('上传七牛云出错');
            }
            $this->success('成功', ['code_url' => $code_url]);
        } else {
            $this->error('请求方式错误');
        }
    }

    //邀请好友获得球币
    public function share()
    {
        if ($this->request->isGet()) {
            $share_member_id = $this->request->get('share_member_id');
            $rule = config('verify.share');
            $this->checkValidate(['share_member_id' => $share_member_id], $rule);

            //查询分享人是否存在
            $is_share = MemberModel::where(['id' => $share_member_id, 'status' => MemberModel::STATUS_NORMAL])->count();
            if (empty($is_share)) {
                $this->error('分享人不存在');
            }

            //分享人错误
            $member_id = $this->getUserId();
            if ($member_id == $share_member_id) {
                $this->error('分享人不能是自己');
            }

            //查询分享人是否已邀请过该好友
            $is_invite = ChangeCoinModel::where(['member_id' => $share_member_id, 'relate_id' => $member_id, 'type' => ChangeCoinModel::INVITE])->count();
            if ($is_invite) {
                $this->error('已邀请过该好友');
            }

            //查询分享人获得球币是否已到上限
            $res_set = InfoSetModel::where('id', 1)->field('id,origin_coin,incre_coin,upper_coin')->find();
            if ($res_set) {
                //查询分享人已获得球币总和
                $res_change_coin = ChangeCoinModel::where(['member_id' => $share_member_id, 'type' => ChangeCoinModel::INVITE])->field('id,change_coin')->select()->toArray();
                $upper_coin = 0;
                foreach ($res_change_coin as $value) {
                    $upper_coin = str_replace('+', '', $value['change_coin']);
                }
                //此上限为为最后的变动球币
                if ($upper_coin > $res_set['upper_coin']) {
                    $this->error('获得球币已达到上限');
                }
                //分享人获得总球币
                $total_coin = $res_set['origin_coin'] + count($res_change_coin) * $res_set['incre_coin'];
                //更新分享人球币
                Db::startTrans();
                $res = MemberModel::where('id', $share_member_id)->setInc('coin', $total_coin);
                //更新球币变动表
                $after_coin = MemberModel::where('id', $share_member_id)->value('coin');
                $res1 = CommonController::changeCoin($share_member_id, ChangeCoinModel::INVITE, $member_id, '邀请新人', '+' . $total_coin, $after_coin);
                //增加邀请人数
                $res2 = MemberModel::where('id',$share_member_id)->setInc('invite_num',1);
                if($res && $res1 && $res2){
                    Db::commit();
                    $this->success('成功');
                } else {
                    Db::rollback();
                    $this->error('失败');
                }
            }
            $this->error('未获取到数据');
        } else {
            $this->error('请求方式错误');
        }
    }

    //邀请记录列表
    public function inviteRecordList()
    {
        if ($this->request->isGet()) {
            $page = $this->request->get('page');
            $rule = config('verify.page');
            $this->checkValidate(['page' => $page], $rule);

            $limit = config('verify.limit');
            $member_id = $this->getUserId();
            $type = ChangeCoinModel::INVITE;
            $res = Db::name('change_coin')
                ->alias('c')
                ->join('member m', 'c.relate_id = m.id', 'LEFT')
                ->where(['c.member_id' => $member_id, 'c.type' => $type,])
                ->field('c.id,c.change_coin,m.nickname,m.avatar')
                ->page($page, $limit)
                ->order('c.id desc')
                ->select()
                ->toArray();
            $total_page = CommonController::totalWherePage('change_coin', ['member_id' => $member_id, 'type' => $type]);
            $this->success('成功', ['data' => $res, 'last_page' => $total_page]);
        } else {
            $this->error('请求方式错误');
        }
    }

    //最近邀请人获得球币列表
    public function inviteRecordLately()
    {
        $result = ChangeCoinModel::field('id,member_id,change_coin')
            ->with(['member' => function( $query ) {
                $query->field('id,province,nickname');
            }])
            ->where('type',ChangeCoinModel::INVITE)
            ->order('create_time desc')
            ->limit(10)
            ->select()
            ->each(function ($item){
                $item->change_coin = substr($item->change_coin,1);
            });
        $this->success('成功', $result);

    }
}
